package com.hjwoo.app.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hjwoo.app.R;
import com.hjwoo.app.been.OnCreateOpt;
import com.hjwoo.app.net.RequestListener;
import com.hjwoo.app.ui.ObservableScrollView;
import com.hjwoo.app.ui.loopviewpager.AutoLoopViewPager;
import com.hjwoo.app.ui.viewpagerindicator.CirclePageIndicator;
import com.hjwoo.app.utils.LoanAccessTokenIdKeeper;
import com.hjwoo.app.utils.LoanLog;
import com.hjwoo.app.utils.LoanToast;
import com.hjwoo.app.views.CommunityActivity;
import com.hjwoo.app.views.HomeWebshowActivity;
import com.hjwoo.app.views.ImmediatelyActivity;
import com.hjwoo.app.views.MainActivity;

import org.xutils.view.annotation.ContentView;

@ContentView(R.layout.fragment_home)
public class HomeFragment extends Fragment implements RequestListener
{

    //    @ViewInject(R.id.pager)
    AutoLoopViewPager pager;

    //    @ViewInject(R.id.indicator)
    CirclePageIndicator indicator;

    //    @ViewInject(R.id.textHeadTitle)
//    TextView textHeadTitle;
//    @ViewInject(R.id.btnBack)
//    Button btnBack;
    RelativeLayout title;
    TextView       textHeadTitle;
    private int[]               imageViewIds;
    private GalleryPagerAdapter galleryAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
//        initView();
    }

    void initView(View view)
    {
        imageViewIds = new int[]{R.drawable.home_banner1};
//        imageViewIds = new int[]{R.drawable.home_banner};
//        imageViewIds = new int[]{R.drawable.home_banner, R.drawable.home_banner, R.drawable.home_banner};


        title = (RelativeLayout) view.findViewById(R.id.home_header_rl);
        textHeadTitle = (TextView) view.findViewById(R.id.headtitle_tv);
        title.setBackgroundColor(Color.argb((int) 255, 249, 100, 6));
        title.getBackground().setAlpha(0);//默认标题栏背景为全透明，必须在已经设置了背景颜色的前提下
        textHeadTitle.setAlpha(0);

        // 通知标题栏刷新显示
//        title.invalidate();
        ObservableScrollView scroll = (ObservableScrollView) view.findViewById(R.id.home_sv);

        /*
        监听ScrollView的滚动，由于在有些系统上无法监听原生ScrollView滚动，导致fc。
        在这里用继承ScrollView的MyScrollView
        */
//        MyScrollView scroll=(MyScrollView)findViewById(R.id.mainScrollView);
        scroll.setOnScrollChangedListener(new ObservableScrollView.OnScrollChangedListener()
        {

            @Override
            public void onScrollChanged(ScrollView who, int x, int y, int oldx, int oldy)

            {
                // TODO: Implement this method
                int titleBarHeight = title.getMeasuredHeight();
//                获取ListView第一个Item高度与标题栏高度差
                int pagerHeight = pager.getMeasuredHeight();

//                textHeadTitle

                if (y <= 0)
                {
                    title.setBackgroundColor(Color.argb((int) 0, 249, 100, 6));//AGB由相关工具获得，或者美工提供
                    textHeadTitle.setAlpha(0);
                }
                else if (y > 0 && y <= pagerHeight)
                {
                    float scale = (float) y / pagerHeight;
                    float alpha = (255 * scale);
                    // 只是layout背景透明(仿知乎滑动效果)
                    title.setBackgroundColor(Color.argb((int) alpha, 249, 100, 6));
                    textHeadTitle.setAlpha(scale);
                }
                else
                {
                    title.setBackgroundColor(Color.argb((int) 255, 249, 100, 6));
                    textHeadTitle.setAlpha(1);

                }
            }
        });


        galleryAdapter = new GalleryPagerAdapter();
        pager = (AutoLoopViewPager) view.findViewById(R.id.pager);
        indicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
        pager.setAdapter(galleryAdapter);
        indicator.setViewPager(pager);
        indicator.setPadding(5, 5, 10, 5);

        view.findViewById(R.id.home_evaluate_btn).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {

                if (!LoanAccessTokenIdKeeper.readAccessToken(HomeFragment.this.getActivity()).getAppSessionId().equals(""))
                {
                    startActivity(new Intent(HomeFragment.this.getActivity(), CommunityActivity.class));
                }
                else
                {
                    //请登录
                    MainActivity.currIndex = 3;
                    MainActivity.showFragment();
                    MainActivity.group.check(R.id.main_footbar_user);
                    LoanToast.showToastShort("请登录", HomeFragment.this.getActivity());

                }

            }
        });
        view.findViewById(R.id.home_evaluate2_btn).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {

                if (!LoanAccessTokenIdKeeper.readAccessToken(HomeFragment.this.getActivity()).getAppSessionId().equals(""))
                {
//                    RequestMethod.getMethod().appCreateOpportunity(HomeFragment.this, HomeFragment.this.getContext());//这里调用接口请求网络
                    Intent intent = new Intent(HomeFragment.this.getContext(), ImmediatelyActivity.class);
                    //直接报单serialnumber传空字符串
                    intent.putExtra("serialNumber", "");
                    intent.putExtra("isHome", true);
                    intent.putExtra("isEvaluate2", true);
                    startActivity(intent);
                }
                else
                {
                    //请登录
                    MainActivity.currIndex = 3;
                    MainActivity.showFragment();
                    MainActivity.group.check(R.id.main_footbar_user);
                    LoanToast.showToastShort("请登录", HomeFragment.this.getActivity());

                }

            }
        });

    }

    @Override
    public void onResume()
    {
        super.onResume();
        pager.startAutoScroll();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        pager.stopAutoScroll();
    }



    //轮播图适配器
    public class GalleryPagerAdapter extends PagerAdapter
    {

        @Override
        public int getCount()
        {
            return imageViewIds.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            ImageView item = new ImageView(HomeFragment.this.getActivity());
            item.setImageResource(imageViewIds[position]);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
            item.setLayoutParams(params);
            item.setScaleType(ImageView.ScaleType.FIT_XY);
            container.addView(item);

            final int pos = position;
            item.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    startActivity(new Intent(HomeFragment.this.getActivity(), HomeWebshowActivity.class));
//                    if (!LoanAccessTokenIdKeeper.readAccessToken(HomeFragment.this.getActivity()).getAppSessionId().equals(""))
//                    {
//                        startActivity(new Intent(HomeFragment.this.getActivity(), CommunityActivity.class));
//                    }
//                    else
//                    {
//                        //请登录
//                        MainActivity.currIndex = 3;
//                        MainActivity.showFragment();
//                        MainActivity.group.check(R.id.main_footbar_user);
//                        LoanToast.showToastShort("请登录", HomeFragment.this.getActivity());
//
//                    }
                }
            });

            return item;
        }

        @Override
        public void destroyItem(ViewGroup collection, int position, Object view)
        {
            collection.removeView((View) view);
        }

    }

    @Override
    public void requestSuccess(String tag, String message) {


//        if (message.equals(RequestTag.APPCREATEOPPORTUNITY)){

            Gson gson = new Gson();
            OnCreateOpt onCreateOpt = gson.fromJson(message, OnCreateOpt.class);

            Intent intent = new Intent(HomeFragment.this.getContext(), ImmediatelyActivity.class);
            //直接报单serialnumber传空字符串
            intent.putExtra("serialNumber", onCreateOpt.getSerialNumber());
            intent.putExtra("isHome", true);
            startActivity(intent);

//        }


    }

    @Override
    public void requestError(String message) {
        LoanLog.e("test","dd"+message);

    }
}